<!--
 * @Author: wuzhen
 * @Date: 2020-01-14 14:34:28
 * @LastEditors: wuzhen
 * @LastEditTime: 2020-04-16 16:23:15
 * @Description: 母版
 -->
<template>
  <div class="page">
    <!-- bar -->
    <div class="page-wrap" ref="pageWrap">
      <div class="page-header">
        <img :src="logoImg" />
        <span>Butter</span>
      </div>
      <div class="page-main">
        <chat-bar></chat-bar>
        <div class="page-chat">
          <transition>
            <router-view />
          </transition>
        </div>
      </div>
    </div>

    <audio :src="mewsMp3" ref="mp3"></audio>
  </div>
</template>

<script>
import ChatBar from "./components/ChatBar";
import message from "./mixins/message";
import { mapGetters, mapMutations, mapActions } from "vuex";
import { Spin, Message } from "view-design";
export default {
  mixins: [message],
  components: {
    ChatBar,
    Spin
  },
  data() {
    return {
      logoImg: require("@/assets/image/logo1.png"),
      mewsMp3: require("@/assets/news.mp3")
    };
  },
  computed: {
    ...mapGetters(["chatMsg", "chatting", "onlineUserIds"])
  },
  mounted() {
    this.showSpin();
    this.$imWebSocket.createSocket();
    window.addEventListener("onmessageWS", this.getMsg);
    this.getClientRect();
    window.onresize = () => {
      this.getClientRect();
    };
    window.addEventListener("beforeunload", e => {
      this.beforeunloadHandler();
      let userAgent = navigator.userAgent;
      let isOpera = userAgent.indexOf("Opera") > -1;
      if (isOpera) {
        //判断是否Opera浏览器
        return "Opera";
      }
      if (userAgent.indexOf("Firefox") > -1) {
        this.unloadHandler();
      } else if (
        userAgent.indexOf("compatible") > -1 &&
        userAgent.indexOf("MSIE") > -1 &&
        !isOpera
      ) {
        const a = e || window.event || null;
        const cy = a.clientY || a.target.event.clientY;
        const ak = a.altKey || a.target.event.altKey;
        if (cy < 0 || ak) {
          this.unloadHandler();
        }
      }
    });
    window.addEventListener("unload", async e => {
      this.unloadHandler(e);
    });
  },
  destroyed() {
    window.removeEventListener("beforeunload", e =>
      this.beforeunloadHandler(e)
    );
    window.removeEventListener("unload", e => this.unloadHandler(e));
  },
  beforeDestroy() {
    window.removeEventListener("onmessageWS", this.getMsg);
  },
  methods: {
    beforeunloadHandler() {
      this._beforeUnload_time = new Date().getTime();
    },
    async unloadHandler() {
      this._gap_time = new Date().getTime() - this._beforeUnload_time;

      //判断是窗口关闭还是刷新
      localStorage.setItem("time", this._gap_time);
      if (this._gap_time <= 5) {
        localStorage.removeItem("vuex");
      }
    },
    ...mapMutations([
      "set_screen",
      "set_online",
      "set_chatMsg",
      "set_onlineUserIds",
      "set_userInfo"
    ]),
    ...mapActions(["getFriendData", "getGroupData", "getChatUsers"]),
    // 初始化数据
    initData() {
      window.addEventListener("online", () => {
        Spin.hide();
        this.set_online(true);
      });
      window.addEventListener("offline", () => {
        this.set_online(false);
        this.showSpin("网络异常，请检查网络");
        this.$imWebSocket.closeScoket();
      });
      this.getFriendUserData();
      // 初始化消息
      this.chatMsg.forEach(v => {
        if (v.msgStatus === 0) {
          v.msgStatus = -1;
        }
      });
      this.set_chatMsg(this.chatMsg);
    },
    // 获取好友列表
    async getFriendUserData() {
      try {
        await this.getFriendData();
        await this.getGroupData();
        Spin.hide();
      } catch (error) {
        Spin.hide();
        throw error;
      }
    },
    // 显示加载效果
    showSpin(text = "") {
      Spin.show({
        render: h => {
          return h(
            "div",
            {
              class: "load-3"
            },
            [
              h("div", {
                class: "line"
              }),
              h("div", {
                class: "line"
              }),
              h("div", {
                class: "line"
              }),
              h(
                "p",
                {
                  class: "tips"
                },
                text
              )
            ]
          );
        }
      });
    },
    //获取主体距离上，左边距
    getClientRect() {
      const mainObj = this.$refs["pageWrap"].getBoundingClientRect();
      this.set_screen({
        x: mainObj.x,
        y: mainObj.y
      });
    },
    // 接送消息
    async getMsg(e) {
      const data = e.detail;
      if (data.onHttpResponseMessage) {
        this.convertResponseMsg(data.onHttpResponseMessage);
      } else if (data.onUserLoginMessage) {
        // socket链接成功
        this.set_userInfo(data.onUserLoginMessage.result);
        this.initData();
      } else if (data.onLoginFailMessage) {
        await this.$store.dispatch("onClearStroage");
        Message.error(data.onLoginFailMessage.retinfo);
        this.$imWebSocket.closeScoket();
        setTimeout(() => {
          Spin.hide();
          this.$router.replace("/");
        }, 1000);
      } else {
        this.convertMsg(data);
      }
    },
    hidePopup() {
      console.log("111");
    }
  },
  watch: {
    $route(newRoute) {
      if (newRoute.name === "chat") {
        for (let index = 0; index < this.chatUsers.length; index++) {
          const current = this.chatUsers[index];
          if (current.id === this.chatting.id) {
            current.total = 0;
            return;
          }
        }
      }
    }
  }
};
</script>

<style lang="less">
.page {
  position: relative;
  height: 100vh;
  min-height: 700px;
  &-wrap {
    position: absolute;
    width: 1000px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    box-shadow: 0 2px 10px #999;
    border-radius: 2px;
    overflow: hidden;
    background: #f5f6fa;
  }
  &-header {
    height: 52px;
    line-height: 52px;
    background: #f8a52c;
    display: flex;
    align-items: center;
    padding: 0 15px;
    img {
      width: 28px;
      height: 26px;
      margin-right: 15px;
    }
    span {
      font-size: 20px;
      color: #fff;
    }
  }
  &-main {
    display: flex;
    overflow: hidden;
    height: 600px;
  }
}
</style>
